package simulation;

import java.util.ArrayList;
import java.util.HashMap;

public class TrackerRequest {

	Integer cid; // chunk id
	HashMap<String, ArrayList<HostRequestedDiagnostic>> hostsList; // list of hosts in each subset
	HashMap<Integer, Boolean> hostIdsToSendUSet; // control the hosts that existed when cid was requested
	double timeout; // time when requests must have been answered
	boolean diagnosticFinished;
	public boolean timeoutSet = false;
	
	/**
	 * Constructor
	 * @param cid Chunk id that this class holds
	 */
	public TrackerRequest(Integer cid){
		this.setCid(cid);
		this.hostsList = new HashMap<String, ArrayList<HostRequestedDiagnostic>>();
		this.hostIdsToSendUSet = new HashMap<Integer, Boolean>();
		this.setDiagnosticFinished(false);
	}
	
	/**
	 * Constructor
	 * @param cid Chunk id that this class holds
	 */
	public TrackerRequest(TrackerRequest tr){
		this.setCid(new Integer(tr.getCid()));
		this.hostsList = new HashMap<String, ArrayList<HostRequestedDiagnostic>>(tr.getHostsList());
		this.hostIdsToSendUSet = new HashMap<Integer, Boolean>(tr.getHostIdsSentUSet());
		this.setDiagnosticFinished(tr.isDiagnosticFinished());
	}
	
	/**
	 * When timeout has reached, finalizes insertion of data, and creates a new group including everyone that haven't answered
	 */
	public void finalizeGrouping() {
		String hash = "Haven't answered"; // if host haven't answered, inserts on a specific set
		
		for (Integer hostId : this.getHostIdsSentUSet().keySet()){
			Boolean answered = this.getHostIdsSentUSet().get(hostId);
			
			// If peer haven't sent U Set
			if (!answered){
				if (!hostId.equals(0)) {
				
					// Check if set of unanswered was created
					if (this.getHostsList().get(hash) == null){
						this.getHostsList().put(hash, new ArrayList<HostRequestedDiagnostic>());
					}
					// ... adds the host that haven't sent U Set
					this.getHostsList().get(hash).add(new HostRequestedDiagnostic(hostId));
				}
			}
		}
		
		this.setDiagnosticFinished(true);
	}
	
	public Integer getCid() {
		return cid;
	}

	public void setCid(Integer cid) {
		this.cid = cid;
	}

	public HashMap<String, ArrayList<HostRequestedDiagnostic>> getHostsList() {
		return hostsList;
	}

	public void setHostsList(
			HashMap<String, ArrayList<HostRequestedDiagnostic>> hostsList) {
		this.hostsList = hostsList;
	}

	public HashMap<Integer, Boolean> getHostIdsSentUSet() {
		return hostIdsToSendUSet;
	}

	public void setHostIdsSentUSet(HashMap<Integer, Boolean> hostIdsSentUSet) {
		this.hostIdsToSendUSet = hostIdsSentUSet;
	}

	public double getTimeout() {
		return timeout;
	}

	public void setTimeout(double timeout) {
		this.timeout = timeout;
	}

	public boolean isDiagnosticFinished() {
		return diagnosticFinished;
	}

	public void setDiagnosticFinished(boolean diagnosticFinished) {
		this.diagnosticFinished = diagnosticFinished;
	}
}
